package com.huiminpay.paymentagent.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.common.constant.AliCodeConstants;
import com.huiminpay.paymentagent.conf.AliConfigParam;
import com.huiminpay.paymentagent.dto.AlipayBean;
import com.huiminpay.paymentagent.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.dto.TradeStatus;
import com.huiminpay.paymentagent.message.PayProducer;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;

/**
 * @ClassName: PayChannelAgentServiceImpl
 * @Package: com.huiminpay.paymentagent.service
 * @Description: 封装交易服务凭证
 * @Author 谢同学
 * @Create 2023/11/29 18:43
 * @Version 1.0
 */
@Service
public class PayChannelAgentServiceImpl implements PayChannelAgentService {
    @Resource
    PayProducer payProducer;


    /**
     * 调用支付宝手机WAP下单接口
     * 使用支付宝提供的SDK进行支付宝手机网站支付的订单创建和返回支付表单
     *
     * @param aliConfigParam 支付渠道参数
     * @param alipayBean     请求支付参数
     * @return
     * @throws BusinessException
     */
    @Override
    public PaymentResponseDTO createPayOrderByAliWAP(AliConfigParam aliConfigParam, AlipayBean alipayBean) throws BusinessException {
        //支付宝渠道参数
        String url = aliConfigParam.getUrl();//支付宝下单地址
//        String url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";//支付宝下单地址
        String appId = aliConfigParam.getAppId();//应用Id
        String privateKey = aliConfigParam.getRsaPrivateKey();//私钥
        String format = aliConfigParam.getFormat();//数据格式
        String charest = aliConfigParam.getCharest();//编码格式
        String alipayPublicKey = aliConfigParam.getAlipayPublicKey();//公钥
        String signtype = aliConfigParam.getSigntype();//签名算法类型

        String notifyUrl = aliConfigParam.getNotifyUrl();//支付结果通知地址
        String returnUrl = aliConfigParam.getReturnUrl();//支付完成返回商户地址

        //获得初始化的AlipayClient
        DefaultAlipayClient client = new DefaultAlipayClient(url, appId, privateKey, format, charest, alipayPublicKey, signtype);

        //封装支付请求信息
        AlipayTradeWapPayRequest payRequest = new AlipayTradeWapPayRequest();
        //请求参数
        payRequest.setNotifyUrl(notifyUrl);
        payRequest.setReturnUrl(returnUrl);

        //封装业务参数
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();//支付宝手机网站支付 模型对象（包含所有的业务参数）

        model.setOutTradeNo(alipayBean.getOutTradeNo());//惠民平台订单
        model.setSubject(alipayBean.getSubject());//订单标题
        model.setTotalAmount(alipayBean.getTotalAmount());//订单金额
        model.setBody(alipayBean.getBody());//订单内容
        model.setTimeoutExpress(alipayBean.getExpireTime());//订单过期时间
        model.setProductCode(alipayBean.getProductCode());//商户与支付宝签定的产品码，固定为QUICK_WAP_WAY

        payRequest.setBizModel(model);//请求参数集合

        String form;
        try {
            //发送支付结果查询延迟信息
            PaymentResponseDTO<AliConfigParam> notice = new PaymentResponseDTO<>();
            notice.setOutTradeNo(alipayBean.getOutTradeNo());
            notice.setContent(aliConfigParam);
            notice.setMsg("ALIPAY_WAP");
            payProducer.payOrderNotice(notice);


            form = client.pageExecute(payRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


        PaymentResponseDTO paymentResponseDTO = new PaymentResponseDTO();//创建支付请求对象
        paymentResponseDTO.setContent(form);

        return paymentResponseDTO;
    }

    /**
     * 支付宝交易状态查询
     *
     * @param aliConfigParam 支付渠道参数
     * @param outTradeNO     惠民平台订单号
     * @return
     */
    @Override
    public PaymentResponseDTO queryPayOrderByAli(AliConfigParam aliConfigParam, String outTradeNO) {
        //支付宝渠道参数
        String url = aliConfigParam.getUrl();//支付宝下单地址
//        String url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";//支付宝下单地址
        String appId = aliConfigParam.getAppId();//应用Id
        String privateKey = aliConfigParam.getRsaPrivateKey();//私钥
        String format = aliConfigParam.getFormat();//数据格式
        String charest = aliConfigParam.getCharest();//编码格式
        String alipayPublicKey = aliConfigParam.getAlipayPublicKey();//公钥
        String signtype = aliConfigParam.getSigntype();//签名算法类型


        //获得初始化的AlipayClient
        DefaultAlipayClient client = new DefaultAlipayClient(url, appId, privateKey, format, charest, alipayPublicKey, signtype);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        JSONObject bizContent = new JSONObject();


        //惠民平台订单号
        bizContent.put("out_trade_no", outTradeNO);
//        bizContent.put("out_trade_no", "20150320010101001");
//bizContent.put("trade_no", "2014112611001004680073956707");
        //封装请求参数
        request.setBizContent(bizContent.toString());


        AlipayTradeQueryResponse response = null;
        PaymentResponseDTO dto;
        try {
            //请求支付宝接口
            response = client.execute(request);

            if (response.isSuccess()) {
                System.out.println("调用成功");
                //将支付宝响应的数据转换为惠民平台的状态
                TradeStatus tradeStatus = covertAliTradeStatusTohuiminCode(response.getTradeStatus());
                dto = PaymentResponseDTO.success(response.getTradeNo(), response.getOutTradeNo(), tradeStatus,
                        response.getMsg() + " " + response.getSubMsg());
                return dto;
            } else {
                dto = PaymentResponseDTO.fail("查询支付宝支付结果异常", outTradeNO, TradeStatus.UNKNOWN);
                return dto;
            }

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将支付宝查询时订单状态trade_status 转换为 惠民订单状态
     *
     * @param aliTradeStatus 支付宝交易状态
     *                       WAIT_BUYER_PAY（交易创建，等待买家付款）
     *                       TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）
     *                       TRADE_SUCCESS（交易支付成功）
     *                       TRADE_FINISHED（交易结束，不可退款）
     * @return
     */
    private TradeStatus covertAliTradeStatusTohuiminCode(String aliTradeStatus) {
        switch (aliTradeStatus) {
            case AliCodeConstants.WAIT_BUYER_PAY:
                return TradeStatus.USERPAYING;
            case AliCodeConstants.TRADE_SUCCESS:
            case AliCodeConstants.TRADE_FINISHED:
                return TradeStatus.SUCCESS;
            default:
                return TradeStatus.FAILED;
        }
    }
}
